/*
 *  Copyright (c) 2013 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.cloopen.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
package com.shengyuan.manage_os.old.ying.erpm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.shengyuan.manage_os.old.ying.erpm.MainApplication;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.os.Environment;
import android.os.StatFs;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;


/**
 * Simple tools.
 * 
 * @version 1.0.0
 *
 */
public final class Utility {

	public static final String CCP_DEMO_PREFERENCE = "CCPDemo_preference";
	public static final String SP_KEY_JOIN_GROUP = "join_group";
	public static final String SP_KEY_PUB_GROUP = "pub_group";
	public static final String SP_KEY_VOICE_ISCHUNKED = "isChunked";
	public static final String SP_KEY_PHONE_NUMBER = "phone_number";
	
	public static final String DEMO_ROOT_STORE = "voiceDemo";
	
	public static void MessageBox(Context context, String text ) {
		Toast.makeText( context,  text, Toast.LENGTH_SHORT).show();
	}
	public static void MessageBox(String text ) {
		Toast.makeText( MainApplication.Instance,  text, Toast.LENGTH_SHORT).show();
	}
	public static ProgressDialog ShowModelDialog(Context context, String text)
	{
     	ProgressDialog mDialog = new ProgressDialog(context);
		mDialog.setMessage(text);
		mDialog.setCanceledOnTouchOutside(false);
		mDialog.setCancelable(false);
		return mDialog;

	}

	/**
	 * 对网络连接状态进行判断
	 * @return  true, 可用； false， 不可用
	 */
	public static boolean isOpenNetwork() {
		ConnectivityManager connManager = 
				(ConnectivityManager) 
				MainApplication.Instance.getSystemService(Context.CONNECTIVITY_SERVICE);
		if(connManager.getActiveNetworkInfo() != null) {
			return connManager.getActiveNetworkInfo().isAvailable();
		}

		return false;
	}
	/**
	 * 是否有外存卡
	 * 
	 * @return
	 */
	public static boolean isExistExternalStore() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 通话时间 格式00:00:00
	 * 
	 * @param duration
	 * @return
	 */
	public static String getCallDurationShow(long duration) {
		if (duration / 60 == 0) {
			String second = "00";

			if (duration < 10) {
				second = "0" + duration;
			} else {
				second = duration + "";
			}
			return "00:" + second;
		} else {
			String minute = "00";
			String second = "00";
			String hour = "00";
			if ((duration / 60) < 10) {
				minute = "0" + (duration / 60);
			} else {
				if ((duration / 60) > 59) {
					if ((duration / 3600) < 10) {
						hour = "0" + (duration / 3600);
					} else {
						hour = (duration / 3600) + "";
					}

					if ((duration / 60) % 60 < 10) {
						minute = "0" + (duration / 60) % 60;
					} else {
						minute = (duration / 60) % 60 + "";
					}

				} else {
					minute = (duration / 60) + "";
				}
			}
			if ((duration % 60) < 10) {
				second = "0" + (duration % 60);
			} else {
				second = (duration % 60) + "";
			}
			if (hour.equals("00")) {
				return minute + ":" + second;
			} else {
				return hour + ":" + minute + ":" + second;
			}
		}
	}
	
	
	static MediaPlayer mediaPlayer = null;
	public static void playNotifycationMusic (Context context ,String voicePath) throws IOException  {
		//paly music ...
		AssetFileDescriptor fileDescriptor = context.getAssets().openFd(voicePath);
		if(mediaPlayer == null ) {
			mediaPlayer = new MediaPlayer();
		}
		if(mediaPlayer.isPlaying()) {
			mediaPlayer.stop();
		}
		mediaPlayer.reset();
		mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),fileDescriptor.getStartOffset(),
				fileDescriptor.getLength());
		mediaPlayer.prepare();
		mediaPlayer.setLooping(false);
		mediaPlayer.start();
	}
	
	public static ArrayList<String> removeString(List<String> strArr,String str){
		ArrayList<String> newArr= null;
		if(strArr!=null&&str!=null){
			newArr = new ArrayList<String>();
			for (String string : strArr) {
				if(!str.equals(string)){
					newArr.add(string);
				}
			}
		}
		return newArr;
	}
	
	public static void registDialog (final Context context) {
		new AlertDialog.Builder(context)
		 .setTitle("") 
		 .setMessage("")
		 	.setPositiveButton("", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					try {
						//VoiceApplication.getInstance().setQuitApplication(true);
						clearActivityTask(context);
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				}

			})
		 	.show();
	}
	
	public static void clearActivityTask(final Context context) {
		Intent i = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()); 
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
		context.startActivity(i);
		((Activity)context).finish();
		
	}
	
	
	public static String getDateCreate() {
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return dateformat.format(new Date());
	}
	
	public static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public static final SimpleDateFormat sequenceFormat = new SimpleDateFormat("yyyyMMddHHmmss");
	public static final String HOLDPLACE = nextHexString(49);
	
	/** The random seed */
	static final long seed = System.currentTimeMillis();
	// static final long seed=0;

	public static int K = 1;
	public static String getSequenceFormat(long t) {
		//long t = System.currentTimeMillis();
		Date d = new Date(t);
		String date = sequenceFormat.format(d);
		
		return date + "$" + (K++) + "%" + HOLDPLACE + "@" + t;
	}
	
	/** Returns a random hexadecimal String */
	public static String nextHexString(int len) {
		byte[] buff = new byte[len];
		for (int i = 0; i < len; i++) {
			int n = nextInt(16);
			buff[i] = (byte) ((n < 10) ? 48 + n : 87 + n);
		}
		return new String(buff);
	}
	
	
	/** Returns a random integer between 0 and n-1 */
	public static int nextInt(int n) {
		Random rand = new Random(seed);
		return Math.abs(rand.nextInt()) % n;
	}
	
	
	// 判断字符串是否包含中文
	public static boolean hasFullSize(String inStr) {
		if (inStr.getBytes().length != inStr.length()) {
			return true;
		}
		return false;
	}
	
	public static final String TACK_PIC_PATH = getExternalStorePath()+  "/" +DEMO_ROOT_STORE + "/.chatTemp";
	public static File TackPicFilePath() {
		File localFile = new File(TACK_PIC_PATH , createCCPFileName() + ".jpg");
		if ((!localFile.getParentFile().exists())
				&& (!localFile.getParentFile().mkdirs())) {
			localFile = null;
		}
		return localFile;
	}
	
	/**
	 * /sdcard
	 *
	 * @return
	 */
	public static String getExternalStorePath() {
		if (isExistExternalStore()) {
			return Environment.getExternalStorageDirectory().getAbsolutePath();
		}
		return null;
	}
	
	
	/**
	 * dip转化像素
	 * @param context
	 * @param dipValue
	 * @return
	 */
	public static int dip2px(Context context, float dipValue){

		final float scale = context.getResources().getDisplayMetrics().density;

		return (int)(dipValue * scale + 0.5f);

	}
	
	
	private static long lastClickTime; 
    public static boolean isInvalidClick() { 
        long time = System.currentTimeMillis(); 
        long timeD = time - lastClickTime; 
        if ( 0 < timeD && timeD < 1000) {    
            return true;    
        }    
        lastClickTime = time;    
        return false;    
    } 
    
    
    public static boolean delFile(String filePath){
    	File file = new File(filePath);
		if (!file.exists()) {
			return true;
		}
		
		return file.delete();
    }

	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * delete all file
	 * @param path
	 * @return
	 */
	public static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}

	public static int getMetricsDensity(Context context , float height) {
		DisplayMetrics localDisplayMetrics = new DisplayMetrics();
		((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay().getMetrics(localDisplayMetrics);
		return Math.round(height * localDisplayMetrics.densityDpi / 160.0F);
	}
	
	
	public static String createCCPFileName() {
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		
		int y = c.get(Calendar.YEAR);
		int m = c.get(Calendar.MONTH);
		int d = c.get(Calendar.DAY_OF_MONTH);
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		int second = c.get(Calendar.SECOND);
		return y + "-" + m  + "-" + d  + "-" + hour + "-" + minute  + "-" + second;
	}
	
	public static boolean createnewfile(String file)
	{
		File f = new File(file);
		try {
			if (!f.exists()) {
			f.createNewFile();
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	public static int GetTimeID() {
		return (int) ( System.currentTimeMillis());
	}
	
	
	 public static long getSDFreeSize( boolean sd){
	      //取得SD卡文件路径
		 File path;
		 if (sd) {
			 path = Environment.getExternalStorageDirectory(); 
		}else {
			path = Environment.getDataDirectory();
		}
	      
	      StatFs sf = new StatFs(path.getPath()); 
	      //获取单个数据块的大小(Byte)
	      long blockSize = sf.getBlockSize(); 
	      //空闲的数据块的数量
	      long freeBlocks = sf.getAvailableBlocks();
	      //返回SD卡空闲大小
	      //return freeBlocks * blockSize;  //单位Byte
	      //return (freeBlocks * blockSize)/1024;   //单位KB
	      return (freeBlocks * blockSize)/1024 /1024; //单位MB
	    }	
	 
	 public static long getSDAllSize(boolean sd){
	      //取得SD卡文件路径
		 File path;
		 if (sd) {
			 path = Environment.getExternalStorageDirectory(); 
		}else {
			path = Environment.getDataDirectory();
		}
	      StatFs sf = new StatFs(path.getPath()); 
	      //获取单个数据块的大小(Byte)
	      long blockSize = sf.getBlockSize();
	      //获取所有数据块数
	      long allBlocks = sf.getBlockCount();
	      //返回SD卡大小
	      //return allBlocks * blockSize; //单位Byte
	      //return (allBlocks * blockSize)/1024; //单位KB
	      return (allBlocks * blockSize)/1024/1024; //单位MB
	    }	
	 
	 public static String getOfflineMapPath() {
		 if (isExistExternalStore()) {
				File fExternalStorageDirectory = Environment
						.getExternalStorageDirectory();
				File autonaviDir = new File(
						fExternalStorageDirectory, "Company");
				boolean result = false;
				if (!autonaviDir.exists()) {
					result = autonaviDir.mkdir();
				}
				File minimapDir = new File(autonaviDir, "Name");
				if (!minimapDir.exists()) {
					result = minimapDir.mkdir();
				}
				return minimapDir.toString() + "/";
		}else {
			return null;
		}
	}

	 public static void InitHideKeyboard( Window win){
			win.setSoftInputMode(               
					WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
	 }
	 
	public static void HideKeyboard1(Context window){
		String INPUT_METHOD_SERVICE = "input_method";
		View view = ((Activity) window).getCurrentFocus();
		if (view!=null) {
			InputMethodManager imm = (InputMethodManager) window.getSystemService(INPUT_METHOD_SERVICE); 
			imm.showSoftInput(view, 0); //显示软键盘 
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0);//隐藏软键盘 
		}
		view.getApplicationWindowToken();
	}
	public static void HideEditFouce(EditText editText)
	{
		String INPUT_METHOD_SERVICE = "input_method";
		if (editText!=null ) {
			InputMethodManager imm = (InputMethodManager) editText.getContext().getSystemService(INPUT_METHOD_SERVICE); 
			//imm.showSoftInput(editText_car, 0); //显示软键盘 
			imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);//隐藏软键盘
		}		
	}
	public static void CreateFolder( String dir) {
		File dirFile = new File(dir+"");
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}
	}
	
	public static void CopyDest(String sfile, String sdest) {
		File file = new File(sfile);
		if (file.exists()) {
			file.renameTo( new File(sdest));
		}
	}
	
	//第一个参数是图片的路径，第二个参数是获取到的缩略图的宽度，第三个参数是获取到的缩略图的高度
	public static Bitmap getImageThumbnail(String imagePath, int width, int height) {
			Bitmap bitmap = null;
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inPreferredConfig = Bitmap.Config.ARGB_4444;
			options.inPurgeable = true;
			options.inInputShareable = true;
			options.inJustDecodeBounds = true;
			// 获取这个图片的宽和高，注意此处的bitmap为null
			bitmap = BitmapFactory.decodeFile(imagePath, options);
			options.inJustDecodeBounds = false; // 设为 false
			// 计算缩放比
			int h = options.outHeight;
			int w = options.outWidth;
			int beWidth = w / width;
			int beHeight = h / height;
			int be = 1;
			if (beWidth < beHeight) {
				be = beWidth;
			} else {
				be = beHeight;
			}
			if (be <= 0) {
				be = 1;
			}
			options.inSampleSize = be;
			// 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
			bitmap = BitmapFactory.decodeFile(imagePath, options);
			// 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
			bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
					ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
			return bitmap;
		}
	
	public static boolean  copyFile(String oldPath, String newPath) { 
		   boolean isok = true;
	       try { 
	           int bytesum = 0; 
	           int byteread = 0; 
	           File oldfile = new File(oldPath); 
	           if (oldfile.exists()) { //文件存在时 
	               InputStream inStream = new FileInputStream(oldPath); //读入原文件 
	               FileOutputStream fs = new FileOutputStream(newPath); 
	               byte[] buffer = new byte[1024]; 
	               int length; 
	               while ( (byteread = inStream.read(buffer)) != -1) { 
	                   bytesum += byteread; //字节数 文件大小 
	                   //System.out.println(bytesum); 
	                   fs.write(buffer, 0, byteread); 
	               } 
	               fs.flush(); 
	               fs.close(); 
	               inStream.close(); 
	           }
	           else
	           {
				isok = false;
			   }
	       } 
	       catch (Exception e) { 
	          // System.out.println("复制单个文件操作出错"); 
	          // e.printStackTrace(); 
	           isok = false;
	       } 
	       return isok;

	   } 
	
	public static  PackageInfo checkPackageManager(Context context, String packages){
		PackageInfo packageInfo= null;
        try {
        	packageInfo = context.getPackageManager().getPackageInfo(
            		packages, 0);
        } catch (NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        return packageInfo;
	}
	
	//在一个应用程序里面启动另一个应用程序
	public static Intent startAppByPackageName(Context context, String packageName){
	   PackageInfo pi = null;  
	   Intent intent = null;
       try {
        pi = context.getPackageManager().getPackageInfo(packageName, 0);  
        } catch (NameNotFoundException e) {  
            e.printStackTrace();  
        }  
           
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);  
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);  
        resolveIntent.setPackage(pi.packageName);  
           
        List<ResolveInfo> apps = context.getPackageManager().queryIntentActivities(resolveIntent, 0);  
          
        ResolveInfo ri = apps.iterator().next();  
        if (ri != null ) {  
            String packageName1 = ri.activityInfo.packageName;  
           String className = ri.activityInfo.name;  
              
           intent = new Intent(Intent.ACTION_MAIN);  
           intent.addCategory(Intent.CATEGORY_LAUNCHER);  
             
            ComponentName cn = new ComponentName(packageName1, className);  
              
           intent.setComponent(cn);  
           //context.startActivity(intent);
       }  
        return intent;
    }
		
}
